package com.tzxs.pay.main.bill;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.arch.lifecycle.ViewModelProviders;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.provider.Settings;
import android.support.annotation.Nullable;
import android.support.design.widget.Snackbar;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.Toast;

import com.tbruyelle.rxpermissions2.RxPermissions;
import com.tzxs.pay.R;
import com.tzxs.pay.databinding.ActivityBillSearchBinding;
import com.tzxs.pay.main.base.BaseActivity;
import com.tzxs.pay.main.bill.detail.AutTncActivity;
import com.tzxs.pay.main.bill.detail.CollAndInstallDetailActivity;
import com.tzxs.pay.main.bill.viewmodel.BillViewModel;
import com.tzxs.pay.util.ScanActivity;
import com.tzxs.pay.util.StatusBarColorSetter;
import com.uuzuche.lib_zxing.activity.CodeUtils;

import java.util.Objects;
import java.util.Timer;
import java.util.TimerTask;

//订单搜索
public class BillSearchActivity extends BaseActivity<ActivityBillSearchBinding> {
    private static final int SCAN_CODE = 100;//扫码
    private static final String TAG = BillSearchActivity.class.getSimpleName();
    private RxPermissions rxPermissions;
    private BillViewModel model;

    @Override
    protected Activity getChildActivity() {
        return this;
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_bill_search;
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        StatusBarColorSetter.setStatusBarColor(this, Color.parseColor("#FAFAFA"));
        model = ViewModelProviders.of(this).get(BillViewModel.class);
        rxPermissions = new RxPermissions(this);
        dataBinding.billSearchToolbar.setTitle("");
        setSupportActionBar(dataBinding.billSearchToolbar);
        showKeyBoard(dataBinding.searchContent);
        dataBinding.back.setOnClickListener(v -> {
            closeKeyBoard();
            onBackPressed();
        });
        //监听提示
        model.snackbarText.observe(this, s -> {
            if (s != null) {
                Snackbar.make(dataBinding.billSearchToolbar, s, Snackbar.LENGTH_SHORT).show();
            }
        });
        //搜索
        dataBinding.search.setOnClickListener(v -> {
            if (TextUtils.isEmpty(dataBinding.searchContent.getText().toString())) {
                Toast.makeText(this, "请输入订单号", Toast.LENGTH_SHORT).show();
                return;
            }
            //查询订单号
            searchOrder(dataBinding.searchContent.getText().toString());
        });
        //扫码
        dataBinding.scan.setOnClickListener(v -> {
            requestScanPermission();
        });
        //搜索内容监听
        dataBinding.searchContent.setOnEditorActionListener((v, actionId, event) -> {
            if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                String orderId = dataBinding.searchContent.getText().toString();
                if (orderId.length() == 0) {
                    Toast.makeText(this, "请输入正确的订单号", Toast.LENGTH_SHORT).show();
                    return false;
                }
                searchOrder(orderId);
            }
            return false;
        });
    }

    //查询订单号
    private void searchOrder(String orderId) {
        model.getCollectionBillDetail(orderId, () -> {
            Intent intent = new Intent(this, CollAndInstallDetailActivity.class);
            intent.putExtra("orderId", orderId);
            startActivity(intent);
        });
    }

    //关闭软键盘
    private void closeKeyBoard() {
        InputMethodManager manager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        View view = getWindow().peekDecorView();
        if (view != null) {
            if (Objects.requireNonNull(manager).isActive()) {
                manager.hideSoftInputFromWindow(view.getWindowToken(), 0);
            }
        }
    }

    //关闭软键盘
    //显示键盘
    private void showKeyBoard(EditText editText) {
        editText.setFocusable(true);
        editText.setFocusableInTouchMode(true);
        editText.requestFocus();
        Timer timer = new Timer();
        timer.schedule(new TimerTask() {
            @Override
            public void run() {
                InputMethodManager imm =
                        (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                Objects.requireNonNull(imm).showSoftInput(editText, 0);
                editText.setSelection(editText.getText().length());
            }
        }, 200);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        Log.d(TAG, "onActivityResult: 走这个方法了么:");
        if (requestCode == SCAN_CODE) {
            if (data != null) {
                Bundle bundle = data.getExtras();
                if (bundle == null) {
                    return;
                }
                if (bundle.getInt(CodeUtils.RESULT_TYPE) == CodeUtils.RESULT_SUCCESS) {
                    String result = bundle.getString(CodeUtils.RESULT_STRING);
                    if (result == null) {
                        return;
                    }
                    boolean strHead = result.contains("fu");
                    Log.d(TAG, "onActivityResult: 小票抬头是fu开头：" + strHead + "结果:" + result);
                    if (result.startsWith("fu")) {//当时预授权订单时
                        Intent intent = new Intent(this, AutTncActivity.class);
                        intent.putExtra("orderId", result);
                        startActivity(intent);
                    } else {//否则是收款订单  或者分期订单  预授权结算后变成普通订单
                        Intent intent = new Intent(this, CollAndInstallDetailActivity.class);
                        intent.putExtra("orderId", result);
                        startActivity(intent);
                    }
                } else if (bundle.getInt(CodeUtils.RESULT_TYPE) == CodeUtils.RESULT_FAILED) {
                    Toast.makeText(this, "解析二维码失败", Toast.LENGTH_LONG).show();
                }
            }
        }
    }

    /**
     * 申请二维码扫描需要的权限
     */
    @SuppressLint("CheckResult")
    private void requestScanPermission() {
        rxPermissions.requestEach(Manifest.permission.CAMERA).subscribe(permission -> {
            if (permission.granted) {
                scanCode();
            } else if (permission.shouldShowRequestPermissionRationale) {
                Toast.makeText(this, "扫描二维码需要相机权限!", Toast.LENGTH_SHORT).show();
            } else {
                Uri packageURI = Uri.parse("package:" + getPackageName());
                Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS, packageURI);
                startActivity(intent);
            }
        });
    }

    //关闭软键盘
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_DOWN) {
            closeKeyBoard();
        }
        return super.onKeyDown(keyCode, event);
    }

    //开始扫描二维码
    private void scanCode() {
        Intent scanIntent = new Intent(this, ScanActivity.class);
        startActivityForResult(scanIntent, SCAN_CODE);
    }
}